﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Threading;

namespace AutomaticScreenshot
{
    class Program
    {
        // 导入 Windows API 函数
        [DllImport("user32.dll")]
        public static extern IntPtr GetDesktopWindow();

        [DllImport("user32.dll")]
        static extern IntPtr GetDC(IntPtr hwnd);

        [DllImport("user32.dll")]
        static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);

        static void Main(string[] args)
        {
            int screenshotCount = 0; // 用于记录截图次数
            string basePath = AppDomain.CurrentDomain.BaseDirectory; // 获取程序所在目录路径

            while (true)
            {
                Bitmap screenshot = CaptureScreen(); // 截取屏幕
                string currentTime = DateTime.Now.ToString("yyyyMMddHHmmss"); // 获取当前时间作为截图时间
                string filename = $"screenshot_{currentTime}.png"; // 构建文件名
                string filePath = System.IO.Path.Combine(basePath, filename); // 构建完整文件路径
                screenshot.Save(filePath, ImageFormat.Png); // 保存截图为 PNG 格式
                screenshot.Dispose(); // 释放位图资源

                Console.WriteLine($"已保存截图：{filename}");

                Thread.Sleep(60000); // 间隔一分钟

                screenshotCount++;
            }
        }

        // 通过 Windows API 截取屏幕
        static Bitmap CaptureScreen()
        {
            IntPtr desktopPtr = GetDesktopWindow();
            IntPtr dc = GetDC(desktopPtr);
            Graphics g = Graphics.FromHdc(dc);

            Rectangle bounds = new Rectangle(0, 0, (int)g.VisibleClipBounds.Width, (int)g.VisibleClipBounds.Height);
            Bitmap screenshot = new Bitmap(bounds.Width, bounds.Height);

            using (Graphics graphics = Graphics.FromImage(screenshot))
            {
                graphics.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
            }

            ReleaseDC(desktopPtr, dc);
            g.Dispose();

            return screenshot;
        }


    }
}
